import {
  checkDynamicForm,
  checkPlatformDynamicForm,
  dynamicFormResetValues,
  dynamicPlatformFormResetValues,
  searchDynamicForm,
  searchPlatformDynamicForm
} from '@/api/dynamic-form';
import { ElMessageBox } from 'element-plus';

// 拿到info字段
export function getInfo(formInfo) {
  return formInfo?.info || {};
}

// 拿到rules字段
export function getRules(formInfo) {
  return getInfo(formInfo).rules || {};
}

// 拿到for循环的key字段
export function getForKey(formInfo) {
  return getInfo(formInfo).name;
}

// 处理级联props
export function getCascaderProps(formInfo) {
  const _info = getInfo(formInfo);
  const _rules = getRules(formInfo);
  return {
    emitPath: false,
    checkStrictly: _rules.check_strictly || false,
    multiple: _info.field_value_type.includes('[]'),
    label: 'name',
    value: 'id',
    children: 'children'
  };
}

// 设置表单rules
export function setRules(formInfo, formData, eachIndex, topExpose) {
  const _rules = getRules(formInfo);
  const _info = getInfo(formInfo);
  if (_info.field_type === 'table') return;
  const field = _info.field;
  const isEach = eachIndex != undefined;
  const formRules = [];
  // 必填校验
  const isRequired = _rules.required;
  const isInMinArr = isEach && eachIndex < _rules.min_array;
  if (isRequired || isInMinArr) {
    formRules.push({
      required: true,
      message: `${_info.name}为必填项`,
      trigger: 'change'
    });
  }

  // 字符串最小长度校验
  if (_rules.min_length) {
    formRules.push({
      min: _rules.min_length,
      message: `${_info.name}至少${_rules.min_length}个字符`,
      trigger: 'change'
    });
  }

  // 唯一性校验
  if (isEach && _rules.unique) {
    formRules.push({
      validator(rule, value, callback) {
        const arrValue = formData[field];
        for (let i = 0; i < arrValue.length; i++) {
          const itemValue = arrValue[i];
          if (i === eachIndex) continue;
          if (itemValue && itemValue === value) {
            return callback(new Error(`${_info.name}不可重复`));
          }
        }
        callback();
      },
      trigger: ['change', 'blur']
    });
  }

  // 远程校验
  if (_rules.remote_check) {
    const blurType = ['input', 'input_number', 'textarea'];
    formRules.push({
      validator(rule, value, callback) {
        if (!value) return callback();
        // 校验登陆账号是否存在于自建站中
        const api = {
          company: checkDynamicForm,
          platform: checkPlatformDynamicForm
        }[topExpose.form_role];
        api({
          form_uni_key: topExpose.form_uni_key,
          field_value: {
            field,
            field_value: isArray(formData[field])
              ? formData[field].filter(item => item !== '' && item != undefined)
              : formData[field],
            field_value_type: _info.field_value_type
          },
          item_value: value,
          values: topExpose.initValues()
        })
          .then(res => {
            if (res.data.success) {
              callback();
            } else {
              callback(new Error(res.data.err));
            }
          })
          .catch(() => {
            callback(new Error('远程校验出错'));
          });
      },
      trigger: blurType.includes(_info.field_type) ? 'blur' : 'change'
    });
  }

  // 正则校验
  if (_rules.exp) {
    formRules.push({
      pattern: new RegExp(decodeURIComponent(_rules.exp)),
      message: `${_info.name}格式不正确`,
      trigger: 'change'
    });
  }

  return formRules;
}

// 初始化动态添加、移除表单项的最大/最小值
export function initDynamicNum(value, min_array, max_array, defaultValue) {
  // 小于最小值，添加
  if (value?.length < min_array) {
    for (let i = value.length; i < min_array; i++) {
      value.push(defaultValue);
    }
  }
  // 大于最大值，删除
  if (value?.length > max_array) {
    value.splice(max_array);
  }
}

// 设置下拉属性disabled
export function setDisabled(list) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    item.disabled = item.available === false;
    if (item.children?.length) setDisabled(item.children);
  }
}

// 处理选中值，如果选中有值，但是下拉没有该选项，则清空
export function initOptionValues(formInfo, formData, opts) {
  const { optionList } = opts;
  const _info = getInfo(formInfo);
  const field = _info.field;
  const multiple = _info.field_value_type.includes('[]');
  const hasMultipValue = multiple && formData[field]?.length;
  const hasValue = !multiple && formData[field];
  if (hasMultipValue || hasValue) {
    return initValue(formInfo, formData, {
      optionList,
      hasMultipValue,
      hasValue
    });
  }
}

// 初始化已有值
function initValue(formInfo, formData, opts) {
  const { optionList, hasMultipValue, hasValue } = opts;
  const _info = getInfo(formInfo);
  const field = _info.field;
  const data = formData[field];
  const ids = [];
  getAllId(optionList, ids, true);
  // 多选数组
  if (hasMultipValue) {
    for (let i = data.length - 1; i >= 0; i--) {
      const item = data[i];
      if (!ids.includes(item)) data.splice(i, 1);
    }
  }
  // 单选字符串/数字
  if (hasValue) {
    if (!ids.includes(data)) delete formData[field];
  }
}

// 拿到所有层级的id onlyAvailable:是否只拿可以选择的id
export function getAllId(list, ids, onlyAvailable) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (onlyAvailable && item.available) ids.push(item.id);
    else if (!onlyAvailable) ids.push(item.id);

    if (item.children?.length) getAllId(item.children, ids, onlyAvailable);
  }
}

// 上传提交校验
export function validUploadData(imgListMap, formList) {
  const formFields = [];
  getAllFields(formList, formFields);
  const keys = Object.keys(imgListMap);
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    if (!formFields.includes(key)) continue;
    const fieldItem = imgListMap[key] || [];
    for (let j = 0; j < fieldItem.length; j++) {
      const item = fieldItem[j];
      if (item.status !== 'success') {
        $msg.warning('有图片正在上传中，请稍等');
        return false;
      }
    }
  }
  return true;
}

// 拿到所有字段field
export function getAllFields(list, fields) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    const _info = getInfo(item);
    if (_info.field && !_info.hidden) fields.push(_info.field);
    if (item.children?.length) getAllFields(item.children, fields);
  }
}

// 是否是数组
export function isArray(value) {
  return Object.prototype.toString.call(value).includes('Array');
}

// 处理下拉事件
export function changeSelect(formInfo, formData, opts) {
  const { oldValue, domRef, topExpose } = opts;
  const _info = getInfo(formInfo);
  if (!_info.field_value_type?.includes('[]')) {
    domRef?.value?.blur?.();
    domRef?.value?.togglePopperVisible?.(false);
  }

  const _change = _info.change || {};
  if (_change.change_alert && oldValue) {
    ElMessageBox({
      title: '提示',
      dangerouslyUseHTMLString: true,
      message: _change.message,
      type: 'warning',
      confirmButtonText: '确认',
      showCancelButton: true
    })
      .then(() => {
        afterAlert({ _change, topExpose, _info, formData });
      })
      .catch(() => {
        formData[_info.field] = oldValue;
      });
    return;
  } else {
    afterAlert({ _change, topExpose, _info, formData });
  }
}

// 提醒后的流程
function afterAlert({ _change, topExpose, _info, formData }) {
  // 清除维格云
  if (_change.actions?.includes('clear_vika')) {
    topExpose.events?.clearVika();
  }
  // 清除字段
  if (_change.actions?.includes('clear_fields')) {
    clearFields(_change.clear_fields, formData, topExpose);
  }
  // 重新渲染
  if (_info.re_rendering) {
    setTimeout(() => {
      topExpose.initFormList();
    }, 0);
  }
}

// 清除字段
function clearFields(clear_fields, formData, topExpose) {
  if (!clear_fields?.length) return;
  const formList = topExpose.formList.value || [];
  clear_fields.forEach(async field => {
    const formInfo = deepList(formList, field);
    formInfo.info.is_cleared = true;
    if (formInfo.info.field_type === 'table') {
      if (formInfo.table?.length) formInfo.table.length = 0;
      await nextTick();
      formData[field].length = 0;
    } else {
      delete formData[field];
    }
  });
}

function deepList(list, field) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (item.info?.field === field) return item;
    if (item.children?.length) {
      const obj = deepList(item.children, field);
      if (obj) return obj;
    }
  }
}

// 将下拉options扁平成对象
export function flatOptionsObj(list, obj) {
  list.forEach(item => {
    obj[item.id] = item;
    if (item.children?.length) flatOptionsObj(item.children, obj);
  });
}

// 获取下拉、单选、多选、级联组件的列表
export function getOptions({ optionList, loading, props }) {
  const _info = getInfo(props.formInfo);
  if (_info.options?.length) {
    afterGetOption({ optionList, props, _info, list: _info.options || [] });
    return;
  }
  loading.value = true;
  const api = {
    company: searchDynamicForm,
    platform: searchPlatformDynamicForm
  }[props.topExpose.form_role];
  api({
    form_uni_key: props.topExpose.form_uni_key,
    field_name: _info.field,
    values: props.topExpose.initValues()
    // search:'' // 搜索的内容 远程搜索可能会用到 目前没有远程搜索
  })
    .then(res => {
      afterGetOption({ optionList, props, _info, list: res.data || [] });
    })
    .finally(() => {
      loading.value = false;
    });
}

// 处理获取options后的操作
function afterGetOption({ props, _info, list, optionList }) {
  optionList.value = list || [];
  const field = _info.field;
  setDisabled(optionList.value);
  initOptionValues(props.formInfo, props.formData, {
    optionList: optionList.value
  });
  setTimeout(() => {
    props.TrendsFormRef?.clearValidate([field]);
  }, 0);
}

// 使用接口添加字段内容
export function fillValue({ _info, fillLoading, topExpose }) {
  fillLoading.value = true;
  const api = {
    company: dynamicFormResetValues,
    platform: dynamicPlatformFormResetValues
  }[topExpose.form_role];
  api({
    field_name: _info.field,
    form_uni_key: topExpose.form_uni_key,
    values: topExpose.initValues()
  })
    .then(() => {
      topExpose.initFormList();
    })
    .finally(() => {
      fillLoading.value = false;
    });
}
